#!/bin/bash

# init host post-reboot
# args:
#   $1: containerd version: 1.4.11
#   $2: kubernetes version: 1.21.3
#   $3: private image registry: hub.atompi.cc
#   $4: private image registry username: demo
#   $5: private image registry password: 123123
#   $6: docker registry mirror: pooj3a7i.mirror.aliyuncs.com

containerd_version=$1
kubernetes_version=$2
private_hub=$3
private_hub_username=$4
private_hub_password=$5
docker_mirror=$6


function echo_g (){
    [ $# -ne 1 ] && return 1
    echo -e "\033[32m$1\033[0m"
}


private_hub_auth=$(echo -ne "$private_hub_username:$private_hub_password" | base64)
: "${docker_mirror:=pooj3a7i.mirror.aliyuncs.com}"


echo_g "install containerd.io"
yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
yum makecache fast
yum -y install containerd.io-${containerd_version} 
if [[ ! 0 -eq `echo $?` ]]; then
    echo "install containerd... failed"
    exit 1
fi


echo_g "config containerd"
cat <<EOF | sudo tee /etc/modules-load.d/containerd.conf
overlay
br_netfilter
EOF

modprobe overlay
modprobe br_netfilter

cat <<EOF | sudo tee /etc/sysctl.d/99-kubernetes-cri.conf
net.bridge.bridge-nf-call-iptables  = 1
net.ipv4.ip_forward               = 1
net.bridge.bridge-nf-call-ip6tables = 1
EOF

sysctl --system


mkdir -p /etc/containerd
containerd config default > /etc/containerd/config.toml

#Modify configuration file
sed -i "s#registry.k8s.io#$private_hub/google_containers#g"  /etc/containerd/config.toml
sed -i 's#SystemdCgroup = false#SystemdCgroup = true#g' /etc/containerd/config.toml
python add_containerd_config.py $private_hub $private_hub_auth 

if [[ ! 0 -eq `echo $?` ]]; then
    echo "config containerd... failed"
    exit 1
fi

systemctl daemon-reload
systemctl enable --now containerd


# Configure the runtime location of the crictl client connection
cat > /etc/crictl.yaml <<EOF
runtime-endpoint: unix:///run/containerd/containerd.sock
image-endpoint: unix:///run/containerd/containerd.sock
timeout: 10
debug: false
EOF


echo_g "install kubelet kubeadm kubectl"
cat <<EOF > /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64/
enabled=1
gpgcheck=0
repo_gpgcheck=0
gpgkey=https://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg https://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
EOF

yum install -y kubelet-${kubernetes_version} kubeadm-${kubernetes_version} kubectl-${kubernetes_version}
if [[ ! 0 -eq `echo $?` ]]; then
    echo "install kubelet... failed"
    exit 1
fi



# Change the configuration of Kubelet to use Contained as the Runtime
cat >/etc/sysconfig/kubelet<<EOF
KUBELET_KUBEADM_ARGS="--container-runtime=remote --runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock"
EOF


# enable kubelet
systemctl daemon-reload
systemctl enable --now kubelet
